package com.Education.Controller;

import com.Education.pojo.User;
import com.Education.server.UserService;
import com.Education.util.*;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ServerErrorException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/wx")
public class UserLoginController {
    private final Log logger = LogFactory.getLog(UserLoginController.class);


    @Autowired
    UserService userService;

    @Autowired
    JwtUtils jwtUtils;


    /**
     * 微信登录
     *
     * @param user     用户
     * @return 登录结果
     */
    @RequestMapping(value = "/userlogin", method = RequestMethod.POST)
    public Object loginByWeixin(@RequestBody User user, HttpServletRequest request, HttpServletResponse resp) throws IOException {

        String username = user.getUsername();
        String password = user.getPassword();

        logger.info("============>>username:"+username+"  =======>>password:"+password);

        //System.out.println("SessionId:"+request.getSession().getId());


        /*
        //不使用jwt时的校验部分
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            subject.login(token);
            Session session = subject.getSession();
            session.setAttribute("subject", subject);
            //return  ResponseUtil.ok("登录成功");
        } catch (AuthenticationException e) {
            return  ResponseUtil.fail(-1,"登录失败");
        }
       */


        //先从数据库判断用户是否存在
        User user2 = userService.getUser(username,password);
        if(user2 != null ){

            logger.info("============>>登录课程表系统成功！");

            //获取入学年份
            String  str1 = user2.getUsername();
            String  firstYear = 20 + str1.substring(2,4);

            //返回jwt信息
            //String jwt = jwtUtils.generateToken(user.getUsername());
            String jwt = jwtUtils.generateToken(username);
            resp.setHeader("Authorization", jwt);
            resp.setHeader("Access-control-Expose-Headers", "Authorization");

            Map<Object, Object> result = new HashMap<Object, Object>();
            result.put("message","登录成功.");
            result.put("token",jwt);
            result.put("firstYear",firstYear);
            return ResponseUtil.ok(result);

        }else {

            logger.info("============>>登录教务系统！");

            User userResult = HttpLoginEduUtil.loginEdu(user);

            if(userResult != null){

                userService.addUser(userResult);

                //获取入学年份
                String  str1 = userResult.getUsername();
                String  firstYear = 20 + str1.substring(2,4);

                //返回jwt信息
                //String jwt = jwtUtils.generateToken(user.getUsername());
                String jwt = jwtUtils.generateToken(username);
                resp.setHeader("Authorization", jwt);
                resp.setHeader("Access-control-Expose-Headers", "Authorization");

                Map<Object, Object> result = new HashMap<Object, Object>();
                result.put("message","登录成功..");
                result.put("token",jwt);
                result.put("firstYear",firstYear);
                return ResponseUtil.ok(result);
            }

            return  ResponseUtil.fail(-1,"登录失败");

        }



    }

    //@RequiresAuthentication
    @GetMapping("/checkToken")
    public Object checkToken(){
        System.out.println("/checkToken============");
        //若能经过jwt校验，token合法，则能正常返回
        return ResponseUtil.ok("token有效！");
    }



    @RequiresAuthentication
    @GetMapping("/logout")
    public Object logout() {
        SecurityUtils.getSubject().logout();
        System.out.println("logout");
        return ResponseUtil.ok(null);
    }

    @RequestMapping(path = "/unauthorized/{message}")
    public Object unauthorized(){
        return ResponseUtil.fail("非法请求");
    }
}
